/*
----------------------------------------------------------------------------
Copyright (c) 2005 - 2008, Wangxing SHI	<swxlion@gmail.com>

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.

* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.

* Neither the copyright holder's name nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------------
*/

/*------------------------------- TRBTree.h -------------------------------*/
/*===========================================================================
FILE: TRBTree.h
Author: Wangxing SHI (swxlion)
Version: 0.0.2 
Date: 2008-03-29

File Description:
    C++ template for the Red Balck Tree.
    This version using iteration rather than recursion achieve.

Require:
    Overload the "<", ">", "==", "=" four operators for type.

Dependencies:
    Platform: Platform Independent.

NOTE:
	If using with the Memory Pool, please DO NOT use the fuanction Clear(),
	Remove( , true), Delete(). And before destroy instance the tree, please ensure
	the tree is empty, because the instance will call the Clear() function in
	the destructor.

History:
version        author        date       description
----------------------------------------------------
0.0.1          swxlion       07-08-08   Created the first version. 
0.0.2          swxlion       08-03-29   Integrated in the ASDL namespace.
===========================================================================*/
#ifndef _APPLICATION_SERVER_DEVELOPMENT_LIBRARY__TRED_BLACK_TREE_H_
#define _APPLICATION_SERVER_DEVELOPMENT_LIBRARY__TRED_BLACK_TREE_H_

/*===============================================================================
CLASS & STRUCTURE DEFINITIONS
=============================================================================== */
namespace ASDL
{
	template <typename Type>
	class TRBTree
	{
	public:
		struct RBNode
		{
			Type		Data;
			RBNode		*Left;
			RBNode		*Right;
			RBNode		*Parent;
			bool		IsBlack;

			RBNode(): Left(0), Right(0), Parent(0), IsBlack(false)
			{
			}
			RBNode(const Type &d): Data(d), Left(0), Right(0), Parent(0), IsBlack(false)
			{
			}
		};

	protected:
		RBNode		*pRoot;
		RBNode		Nil;

		void		RotateLeft( RBNode * pTree, RBNode * &pNewTree );
		void		RotateRight( RBNode * pTree, RBNode * &pNewTree );

		void		Insert_Fixup( RBNode * pNode );
		void		Delete_Fixup( RBNode * pNode );
		//void		Nil_Fixup( RBNode * pNode );
		void		Nil_Fixup();

		RBNode *	FindMin( RBNode * pNode )		// Just apply to children, not apply the whole tree.
		{
			while( pNode->Left )
				pNode = pNode->Left;

			return pNode;
		}

		RBNode *	FindMax( RBNode * pNode )		// Just apply to children, not apply the whole tree.
		{
			while( pNode->Right )
				pNode = pNode->Right;

			return pNode;
		}

	public:
		int			Insert( RBNode * pNode, bool bReplace = true );
		void		Remove( RBNode * &pNode, bool bDelete = false );

		void		Remove( const Type &T, bool bDelete = false )
		{
			RBNode	*pNode = Find(T);
			Remove( pNode, bDelete );
		}

		void		Delete( RBNode * &pNode )
		{
			Remove( pNode, true );
		}

		void		Delete( const Type &T )
		{
			RBNode	*pNode = Find(T);
			Remove( pNode, true );
		}

		void		Clear();

	public:
		TRBTree(): pRoot(0), Nil()
		{
			Nil.IsBlack = true;
		}
		~TRBTree()
		{
			Clear();
		}

		//-- Find ----------------------------------
		RBNode *	Find( RBNode * pNode )
		{
			if( !pRoot )
				return NULL;

			RBNode*	pFind = pRoot;
			while( pFind )
			{
				if( pFind->Data == pNode->Data )
					return pFind;
				else if( pFind->Data > pNode->Data )
					pFind = pFind->Left;
				else
					pFind = pFind->Right;
			}
			return NULL;
		}

		RBNode *	Find( Type *pT )
		{
			if( !pRoot )
				return NULL;

			RBNode*	pFind = pRoot;
			while( pFind )
			{
				if( pFind->Data == *pT )
					return pFind;
				else if( pFind->Data > *pT )
					pFind = pFind->Left;
				else
					pFind = pFind->Right;
			}
			return NULL;
		}

		RBNode *	Find( const Type &T )
		{
			if( !pRoot )
				return NULL;

			RBNode*	pFind = pRoot;
			while( pFind )
			{
				if( pFind->Data == T )
					return pFind;
				else if( pFind->Data > T )
					pFind = pFind->Left;
				else
					pFind = pFind->Right;
			}
			return NULL;
		}

		RBNode *	FindMin()
		{
			if( pRoot == NULL )
				return NULL;

			return FindMin(pRoot);
		}

		RBNode *	FindMax()
		{
			if( pRoot == NULL )
				return NULL;

			return FindMax(pRoot);
		}

		RBNode *	GetNext( RBNode * pNode )
		{
			if( !pNode )
				return NULL;

			RBNode * pFindNode = NULL;
			RBNode * pParentNode = pNode->Right;

			if( pParentNode )
			{
				pFindNode = pParentNode->Left;
				while( pFindNode )
				{
					pParentNode = pFindNode;
					pFindNode = pParentNode->Left;
				}
				return pParentNode;
			}
			else
			{
				pFindNode = pNode;
				while( 1 )
				{
					pParentNode = pFindNode->Parent;
					if( !pParentNode )
						return NULL;
					if( pParentNode->Left == pFindNode )
						return pParentNode;
					pFindNode = pParentNode;
				}
			}

			return NULL;
		}

		RBNode *	GetPrevious( RBNode * pNode )
		{
			if( !pNode )
				return NULL;

			RBNode * pFindNode = NULL;
			RBNode * pParentNode = pNode->Left;

			if( pParentNode )
			{
				pFindNode = pParentNode->Right;
				while( pFindNode )
				{
					pParentNode = pFindNode;
					pFindNode = pParentNode->Right;
				}
				return pParentNode;
			}
			else
			{
				pFindNode = pNode;
				while( 1 )
				{
					pParentNode = pFindNode->Parent;
					if( !pParentNode )
						return NULL;
					if( pParentNode->Right == pFindNode )
						return pParentNode;
					pFindNode = pParentNode;
				}
			}

			return NULL;
		}

		RBNode *	FindLarger( const Type &T )
		{
			if( !pRoot )
				return NULL;

			RBNode*	pFind = pRoot;
			RBNode*	pLastFind = NULL;
			while( pFind )
			{
				if( pFind->Data > T )
				{
					pLastFind = pFind;
					pFind = pFind->Left;
				}
				else	//-- pFind->Data <= T
					pFind = pFind->Right;
			}
			return pLastFind;
		}

		RBNode *	FindSmaller( const Type &T )
		{
			if( !pRoot )
				return NULL;

			RBNode*	pFind = pRoot;
			RBNode*	pLastFind = NULL;
			while( pFind )
			{
				if( pFind->Data < T )
				{
					pLastFind = pFind;
					pFind = pFind->Right;
				}
				else	//-- pFind->Data >= T
					pFind = pFind->Left;
			}
			return pLastFind;
		}
	};

	/*===============================================================================
	  FUNCTION DEFINITIONS: Red Black Tree Functions
	=============================================================================== */
	/*===========================================================================

	FUNCTION: TRBTree<Type>::RotateLeft

	DESCRIPTION:
	Left alone rotation.

	PARAMETERS:
	pTree [in] - The subtree require to be adjusted.
	NewTree [out] - The subtree adjusted.

	RETURN VALUE:
	None.

	Comment:
	Do the same operation with the AVL Tree.
	===========================================================================*/
	template <typename Type>
	void TRBTree<Type>::RotateLeft( RBNode * pTree, RBNode * &pNewTree )
	{
		pNewTree = pTree->Right;
		pNewTree->Parent = pTree->Parent;
		pTree->Right = pNewTree->Left;
		if( pNewTree->Left )
			pNewTree->Left->Parent = pTree;
		pNewTree->Left = pTree;
		pTree->Parent = pNewTree;
	}

	/*===========================================================================

	FUNCTION: TRBTree<Type>::RotateRight

	DESCRIPTION:
	Right alone rotation.

	PARAMETERS:
	pTree [in] - The subtree require to be adjusted.
	NewTree [out] - The subtree adjusted.

	RETURN VALUE:
	None.

	Comment:
	Do the same operation with the AVL Tree.
	===========================================================================*/
	template <typename Type>
	void TRBTree<Type>::RotateRight( RBNode * pTree, RBNode * &pNewTree )
	{
		pNewTree = pTree->Left;
		pNewTree->Parent = pTree->Parent;
		pTree->Left = pNewTree->Right;
		if( pNewTree->Right )
			pNewTree->Right->Parent = pTree;
		pNewTree->Right = pTree;
		pTree->Parent = pNewTree;
	}

	/*===========================================================================

	FUNCTION: TRBTree<Type>::Insert

	DESCRIPTION:
	Insert new node in the tree. (Iteration version.)

	PARAMETERS:
	pNode    [in] - The new node will be inserted in the tree.
	bReplace [in] - When the data of the pNode has already existed in the tree,
	              "true" will replace the old value, "false" do nothing.

	RETURN VALUE:
	0 - Succeed.
	1 - The data of the pNode has already existed in the tree, replace or not just
	    according the "bReplace" sign.

	NOTICE:
	Only the value of node be replaced, not the instance of the node.
	===========================================================================*/
	template <typename Type>
	int TRBTree<Type>::Insert( RBNode * pNode, bool bReplace )
	{
		if( !pNode )
			return 0;

		pNode->Left = NULL;
		pNode->Right = NULL;
		pNode->Parent = NULL;
		pNode->IsBlack = false;

		if( !pRoot )
		{
			pRoot = pNode;
			pNode->IsBlack = true;
			return 0;
		}

		register RBNode *		pParentNode = pRoot;

		do
		{
			if( pParentNode->Data > pNode->Data )
			{
				if( pParentNode->Left )
					pParentNode = pParentNode->Left;
				else
				{
					pParentNode->Left = pNode;
					pNode->Parent = pParentNode;
					break;
				}
			}
			else if( pParentNode->Data < pNode->Data )
			{
				if( pParentNode->Right )
					pParentNode = pParentNode->Right;
				else
				{
					pParentNode->Right = pNode;
					pNode->Parent = pParentNode;
					break;
				}
			}
			else if( pParentNode->Data == pNode->Data )
			{
				if( bReplace )
					pParentNode->Data = pNode->Data;
				return 1;
			}
		}
		while(1);

		Insert_Fixup( pNode );

		return 0;
	}

	template <typename Type>
	void TRBTree<Type>::Insert_Fixup( RBNode * pNode )
	{
		RBNode * pTempPtr = NULL;

		while( pNode != pRoot && pNode->Parent->IsBlack == false )
		{
			if( pNode->Parent == pNode->Parent->Parent->Left )
			{
				pTempPtr = pNode->Parent->Parent->Right;
				if( pTempPtr != NULL && pTempPtr->IsBlack == false )
				{
					pNode->Parent->IsBlack = true;
					pTempPtr->IsBlack = true;
					pNode->Parent->Parent->IsBlack = false;
					pNode = pNode->Parent->Parent;
				}
				else
				{
					if( pNode == pNode->Parent->Right )
					{
						pNode = pNode->Parent;
						RotateLeft( pNode, pNode->Parent->Left );	//-- pNode == pNode->Parent->Left.
					}

					pNode->Parent->IsBlack = true;
					pNode->Parent->Parent->IsBlack = false;

					if( pNode->Parent->Parent->Parent == NULL )
						RotateRight( pNode->Parent->Parent, pRoot );
					else
					{
						if( pNode->Parent->Parent == pNode->Parent->Parent->Parent->Left )
							RotateRight( pNode->Parent->Parent, pNode->Parent->Parent->Parent->Left );
						else
							RotateRight( pNode->Parent->Parent, pNode->Parent->Parent->Parent->Right );
					}
				}
			}
			else
			{
				pTempPtr = pNode->Parent->Parent->Left;
				if( pTempPtr != NULL && pTempPtr->IsBlack == false )
				{
					pNode->Parent->IsBlack = true;
					pTempPtr->IsBlack = true;
					pNode->Parent->Parent->IsBlack = false;
					pNode = pNode->Parent->Parent;
				}
				else
				{
					if( pNode == pNode->Parent->Left )
					{
						pNode = pNode->Parent;
						RotateRight( pNode, pNode->Parent->Right );	//-- pNode == pNode->Parent->Right.
					}

					pNode->Parent->IsBlack = true;
					pNode->Parent->Parent->IsBlack = false;

					if( pNode->Parent->Parent->Parent == NULL )
						RotateLeft( pNode->Parent->Parent, pRoot );
					else
					{
						if( pNode->Parent->Parent == pNode->Parent->Parent->Parent->Left )
							RotateLeft( pNode->Parent->Parent, pNode->Parent->Parent->Parent->Left );
						else
							RotateLeft( pNode->Parent->Parent, pNode->Parent->Parent->Parent->Right );
					}
				}
			}//end if( pNode->Parent == pNode->Parent->Parent->Left )
		}//end while( pNode != pRoot && pNode->Parent->IsBlack == false )

		pRoot->IsBlack = true;
	}

	/*===========================================================================

	FUNCTION: TRBTree<Type>::Remove

	DESCRIPTION:
	Remove the specified node from the tree. (Iteration version.)

	PARAMETERS:
	pNode   [in] - The node will be removed from the tree.
	bDelete [in] - true: Remove and delete the specified node;
	               false: Just only remove, but not delete.

	RETURN VALUE:
	None.
	===========================================================================*/
	template <typename Type>
	void TRBTree<Type>::Remove( RBNode * &pNode, bool bDelete )
	{
		if( !pNode )
			return;

		RBNode * pTempPtr = NULL;

		//-- Part.1: Adjust the node which will be removed.
		if( pNode ->Left && pNode->Right )
		{
			RBNode *		temp = FindMin( pNode->Right );			// According the algorithm of the function FindMin, the temp isn't able to have the left-node at the moment.
			pNode->Data = temp->Data;
			pNode = temp;
		}

		//--Part.2: Adjust the pointers.
		RBNode *		pParentNode = pNode->Parent;		//-- maybe null
		if( !pNode->Parent )			//-- Root node: pRoot.
		{
			pRoot = ( pNode->Left != 0 ? pNode->Left : pNode->Right );
			if( pRoot )
			{
				pRoot->Parent = NULL;
				pRoot->IsBlack = true;
			}
			
			if( bDelete )
			{
				delete pNode;
				pNode = NULL;
			}

			return;
		}

		//--  At the moment, the pNode has only one sub node or not.
		if( pParentNode->Left == pNode )
		{
			pParentNode->Left = ( pNode->Left != 0 ? pNode->Left : pNode->Right );
			if( pParentNode->Left )
			{
				pParentNode->Left->Parent = pParentNode;
			}
			else
			{
				pParentNode->Left = &Nil;
				Nil.Parent = pParentNode;
				Nil.IsBlack = true;
				Nil.Left = Nil.Right = NULL;
			}
			pTempPtr = pParentNode->Left;
		}
		else		//-- Include the status of equal.
		{
			pParentNode->Right = ( pNode->Left != 0 ? pNode->Left : pNode->Right );
			if( pParentNode->Right )
			{
				pParentNode->Right->Parent = pParentNode;
			}
			else
			{
				pParentNode->Right = &Nil;
				Nil.Parent = pParentNode;
				Nil.IsBlack = true;
				Nil.Left = Nil.Right = NULL;
			}
			pTempPtr = pParentNode->Right;
		}

		//--Part.3: Adjust the balance of the tree.
		if( pNode->IsBlack == true )
			Delete_Fixup( pTempPtr );

		if( Nil.Parent )
			Nil_Fixup();
		
		if( bDelete )
		{
			delete pNode;
			pNode = NULL;
		}
	}

	template <typename Type>
	void TRBTree<Type>::Delete_Fixup( RBNode * pNode )
	{

		RBNode * pBrotherNode = NULL;

		while( pNode != pRoot && pNode->IsBlack == true )
		{
			if( pNode == pNode->Parent->Left )
			{
				pBrotherNode = pNode->Parent->Right;

				//-- According the context, the pBrotherNode must be existed.

				if( pBrotherNode->IsBlack == false )
				{
					pBrotherNode->IsBlack = true;
					pNode->Parent->IsBlack = false;

					if( pNode->Parent->Parent == NULL )
						RotateLeft( pNode->Parent, pRoot );
					else
					{
						if( pNode->Parent == pNode->Parent->Parent->Left )
							RotateLeft( pNode->Parent, pNode->Parent->Parent->Left );
						else
							RotateLeft( pNode->Parent, pNode->Parent->Parent->Right );
					}
					pBrotherNode = pNode->Parent->Right;
				}

				//-- According the context, the pBrotherNode must be the black.
				if( (pBrotherNode->Left == NULL || pBrotherNode->Left->IsBlack == true)
					&& (pBrotherNode->Right == NULL || pBrotherNode->Right->IsBlack == true) )
					//if( pBrotherNode->Left != NULL && pBrotherNode->Left->IsBlack == true
					//	&& pBrotherNode->Right != NULL && pBrotherNode->Right->IsBlack == true )
				{
					pBrotherNode->IsBlack = false;
					pNode = pNode->Parent;
				}
				else
				{
					if( pBrotherNode->Right == NULL || pBrotherNode->Right->IsBlack == true )
						//if( pBrotherNode->Right != NULL && pBrotherNode->Right->IsBlack == true )
					{
						//-- According the context, the pBrotherNode->Left must be existed, and its color must be the red.
						pBrotherNode->Left->IsBlack = true;
						pBrotherNode->IsBlack = false;
						RotateRight( pBrotherNode, pBrotherNode->Parent->Right );
						pBrotherNode = pNode->Parent->Right;
					}

					pBrotherNode->IsBlack = pNode->Parent->IsBlack;
					pNode->Parent->IsBlack = true;
					pBrotherNode->Right->IsBlack = true;

					if( pNode->Parent->Parent == NULL )
						RotateLeft( pNode->Parent, pRoot );
					else
					{
						if( pNode->Parent == pNode->Parent->Parent->Left )
							RotateLeft( pNode->Parent, pNode->Parent->Parent->Left );
						else
							RotateLeft( pNode->Parent, pNode->Parent->Parent->Right );
					}
					pNode = pRoot;		//-- or break;
				}
			}
			else
			{
				pBrotherNode = pNode->Parent->Left;

				//	if( pBrotherNode == NULL )
				//		break;

				if( pBrotherNode->IsBlack == false )
				{
					pBrotherNode->IsBlack = true;
					pNode->Parent->IsBlack = false;

					//	RotateRight( pNode, pNode->Parent->Right );
					//printf("rotate A\n");
					if( pNode->Parent->Parent == NULL )
						RotateRight( pNode->Parent, pRoot );
					else
					{
						if( pNode->Parent == pNode->Parent->Parent->Left )
							RotateRight( pNode->Parent, pNode->Parent->Parent->Left );
						else
							RotateRight( pNode->Parent, pNode->Parent->Parent->Right );
					}
					pBrotherNode = pNode->Parent->Left;
				}

				if( (pBrotherNode->Left == NULL || pBrotherNode->Left->IsBlack == true)
					&& (pBrotherNode->Right == NULL || pBrotherNode->Right->IsBlack == true) )
					//if( pBrotherNode->Left != NULL && pBrotherNode->Left->IsBlack == true
					//	&& pBrotherNode->Right != NULL && pBrotherNode->Right->IsBlack == true )
				{
					pBrotherNode->IsBlack = false;
					pNode = pNode->Parent;
				}
				else
				{
					if( pBrotherNode->Left == NULL || pBrotherNode->Left->IsBlack == true )
						//if( pBrotherNode->Left != NULL && pBrotherNode->Left->IsBlack == true )
					{
						//-- According the context, the pBrotherNode->Right must be existed, and its color must be red.
						pBrotherNode->Right->IsBlack = true;
						pBrotherNode->IsBlack = false;
						//printf("rotate B\n");
						RotateLeft( pBrotherNode, pBrotherNode->Parent->Left );
						pBrotherNode = pNode->Parent->Left;
					}

					pBrotherNode->IsBlack = pNode->Parent->IsBlack;
					pNode->Parent->IsBlack = true;
					pBrotherNode->Left->IsBlack = true;

					if( pNode->Parent->Parent == NULL )
						RotateRight( pNode->Parent, pRoot );
					else
					{
						if( pNode->Parent == pNode->Parent->Parent->Left )
							RotateRight( pNode->Parent, pNode->Parent->Parent->Left );
						else
							RotateRight( pNode->Parent, pNode->Parent->Parent->Right );
					}
					pNode = pRoot;		//-- or break;
				}
			}
		}

		pNode->IsBlack = true;
	}

	//template <typename Type>
	//void TRBTree<Type>::Nil_Fixup( RBNode * pNode )
	//{
	//	if( pNode->Parent )
	//	{
	//		if(pNode == pNode->Parent->Left)
	//			pNode->Parent->Left = NULL;
	//		else
	//			pNode->Parent->Right = NULL;
	//
	//		pNode->Parent = NULL;
	//	}
	//}

	template <typename Type>
	void TRBTree<Type>::Nil_Fixup()
	{
		if( Nil.Parent )
		{
			if(&Nil == Nil.Parent->Left)
				Nil.Parent->Left = NULL;
			else
				Nil.Parent->Right = NULL;

			Nil.Parent = NULL;
		}
	}


	template <typename Type>
	void TRBTree<Type>::Clear()
	{
		//-- Too slowly.
		//while( pRoot )
		//	Remove( pRoot, true );

		if( !pRoot )
			return;

		RBNode			*lpFindNode = pRoot;
		RBNode			*lpDeleteNode = NULL;

		while( lpFindNode )
		{
			if( lpFindNode->Left )
				lpFindNode = lpFindNode->Left;
			else if( lpFindNode->Right )
				lpFindNode = lpFindNode->Right;
			else
			{
				lpDeleteNode = lpFindNode;
				lpFindNode = lpFindNode->Parent;

				if( lpDeleteNode->Parent ) //-- Now, lpDeleteNode->Parent is lpFindNode. Just for eliminating data dependence.
				{
					if( lpFindNode->Left == lpDeleteNode )
						lpFindNode->Left = NULL;
					else if( lpFindNode->Right == lpDeleteNode )
						lpFindNode->Right = NULL;
				}

				delete lpDeleteNode;
			}
		}
		pRoot = NULL;
	}
}

#endif // _APPLICATION_SERVER_DEVELOPMENT_LIBRARY__TRED_BLACK_TREE_H_
